package com.telit.android.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Maps;
import com.telit.common.core.utils.FeignUtils;
import com.telit.common.enums.ResultCode;
import com.telit.common.exception.ForestBaseException;
import com.telit.common.util.LanguageUtils;
import com.telit.common.util.RedisUtils;
import com.telit.upms.feign.RemoteUpmsService;
import com.telit.upms.vo.MicroSysUserAllInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Auther amy
 * @Describe 用户信息获取业务层
 */
@Service
@Slf4j
public class UserInfoService {

    @Autowired
    private RemoteUpmsService remoteUpmsService;


    /**
     * 获取单个用户信息
     *
     * @return
     */
    public MicroSysUserAllInfoVo getUserInfo(Long id) {
        if (id != null) {
            com.telit.common.core.utils.Result<Map<Long, MicroSysUserAllInfoVo>> selectUserContainDeptAndRoleWithBatchIdsResult = remoteUpmsService.selectUserContainDeptAndRoleWithBatchIds(
                    Arrays.asList(id), true);
            Map<Long, MicroSysUserAllInfoVo> longMicroSysUserAllInfoVoMap = FeignUtils.unwrap(
                    selectUserContainDeptAndRoleWithBatchIdsResult);
            MicroSysUserAllInfoVo microSysUserAllInfoVo = longMicroSysUserAllInfoVoMap.get(id);
            if (microSysUserAllInfoVo == null) {
                throw new ForestBaseException(LanguageUtils.codeMessage(ResultCode.OPERATE_ERROR.getCode(), id));
            }
            return microSysUserAllInfoVo;
        }
        return null;
    }

    /**
     * 获取所有用户信息
     *
     * @return
     */
//    public List<SysUserShortVo> getAllUser(SysUserPageDto sysUserPageDto) {
//        Result<List<SysUserShortVo>> result = upmsFeignClient.getListForCustomer(sysUserPageDto);
//        if (result.getCode().equals(ResultCode.SUCCESS.getCode()) && result.getData() != null) {
//
//            return JSON.parseArray(JSON.toJSONString(result.getData()), SysUserShortVo.class);
//        }
//        return null;
//    }

    /**
     * 根据id获取用户信息
     * @return
     */
//    public SysUserVo getUserFromRedis(Long id){
//        // 如果存在就从redis中获取
//        String key = RedisConstants.SYS_USER_INFO_REDIS_SUFFIX;
//        Object info = RedisUtils.getBoundHash(key,String.valueOf(id));
//        if(info != null){
//            return JSON.parseObject(info.toString(),SysUserVo.class);
//        }
//
//        // 如果不存在就去查询统一平台
//        ResultVo<SysUserVo> resultVo = adminFeignClient.userInfo(id);
//        if(resultVo == null || resultVo.getData() == null){
//            return null;
//        }
//
//        RedisUtils.setBoundHash(key,String.valueOf(id), JSON.toJSONString(resultVo.getData()));
//        return resultVo.getData();
//    }

    /**
     * 校验验证码是否正确
     *
     * @param key
     * @param code
     */
    public void checkSmsCode(String key, String code) {
        if (RedisUtils.exists(key)) {
            String validCode = RedisUtils.get(key);
            if (!code.equalsIgnoreCase(validCode)) {
                throw new ForestBaseException("验证码输入错误");
            }
            return;
        }
        throw new ForestBaseException("验证码已失效,请重新发送");
    }

//    /**
//     * 查询护林员数量
//     *
//     * @param districtCode
//     * @param status
//     * @param name
//     * @return
//     */
//    public int countByCondition(String districtCode, Integer status, String name) {
//        SysUserRolePageDto param = new SysUserRolePageDto();
//        param.setRoleCode(RoleCodeConstants.ROLE_CODE_FORESTER);
//        param.setUserName(name);
//        param.setOnlineStatus(status);
//        param.setRegionCode(districtCode);
//        Result vo = upmsFeignClient.getCountForRole(param);
//        if (vo == null) {
//            log.error("获取护林员数量信息失败");
//            return 0;
//        }
//        return vo.getData() != null ? JSON.parseObject(JSON.toJSON(vo.getData()).toString(), int.class) : 0;
//    }

    public List<MicroSysUserAllInfoVo> queryUserInfoByIds(List<Long> recieverIdList) {
        if (recieverIdList != null && recieverIdList.size() > 0) {
            com.telit.common.core.utils.Result<Map<Long, MicroSysUserAllInfoVo>> selectUserContainDeptAndRoleWithBatchIdsResult = remoteUpmsService.selectUserContainDeptAndRoleWithBatchIds(
                    recieverIdList, true);
            Map<Long, MicroSysUserAllInfoVo> longMicroSysUserAllInfoVoMap = FeignUtils.unwrap(
                    selectUserContainDeptAndRoleWithBatchIdsResult);

            List<MicroSysUserAllInfoVo> microSysUserAllInfoVos = recieverIdList.stream().map(
                    longMicroSysUserAllInfoVoMap::get).collect(Collectors.toList());

            return microSysUserAllInfoVos;
        }
        return null;
    }

//    /**
//     * 临时处理，查询用户信息 不考虑用户删除，部门删除
//     *
//     * @param recieverIdList
//     * @return
//     */
//    public List<SysUserDetailVo> queryUserInfoByIdsNorDelete(List<Long> recieverIdList) {
//        if (recieverIdList != null && recieverIdList.size() > 0) {
//            Result<List<SysUserInfoVo>> sysUserDetailVoResult = upmsFeignClient.queryUserInfoByIdsNorDelete(recieverIdList);
//            if (sysUserDetailVoResult.getCode().equals(ResultCode.SUCCESS.getCode()) && sysUserDetailVoResult.getData() != null && sysUserDetailVoResult.getData() != null) {
//                return JSON.parseArray(JSON.toJSONString(sysUserDetailVoResult.getData()), SysUserDetailVo.class);
//            }
//        }
//        return null;
//    }

    /**
     * 根据传入的ids 获取 id 对应的用户名
     *
     * @param ids 集合id
     *
     * @return 查询结果集
     */
    public Map<Long, String> findAndConvertUserInfoByIds(List<Long> ids) {
        final Map<Long, String> result = Maps.newHashMap();
        final List<Long> queryParam = ids.parallelStream()
                //过滤掉空id
                .filter(ObjectUtil::isNotEmpty)
                //去重
                .distinct()
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(queryParam)) {
            return result;
        }
        final List<MicroSysUserAllInfoVo> vos = queryUserInfoByIds(queryParam);
        if (CollUtil.isEmpty(vos)) {
            return result;
        }
        result.putAll(vos.parallelStream()
                .collect(Collectors.toMap(MicroSysUserAllInfoVo::getId, MicroSysUserAllInfoVo::getRealName)));
        return result;
    }

//    /**
//     * 根据传入的ids 获取 id 对应的用户名
//     *
//     * @param ids 集合id
//     *
//     * @return 查询结果集
//     */
//    public Map<Long, MicroSysUserAllInfoVo> findAndConvertUserInfoByIdsEndWithVo(List<Long> ids) {
//        final Map<Long, MicroSysUserAllInfoVo> result = Maps.newHashMap();
//        final List<Long> queryParam = ids.parallelStream()
//                //过滤掉空id
//                .filter(ObjectUtil::isNotEmpty)
//                //去重
//                .distinct()
//                .collect(Collectors.toList());
//        if (CollUtil.isEmpty(queryParam)) {
//            return result;
//        }
//        final List<MicroSysUserAllInfoVo> vos = queryUserInfoByIds(queryParam);
//        if (CollUtil.isEmpty(vos)) {
//            return result;
//        }
//        result.putAll(vos.parallelStream()
//                .collect(Collectors.toMap(MicroSysUserAllInfoVo::getId, v -> v)));
//        return result;
//    }
}
